package com.huluobo.base.net

import android.util.Log
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.SPUtils
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import org.json.JSONObject

/**
 *  Created by LC on 2024/7/25.
 *  签名拦截器
 */
class SignInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val builder = request.newBuilder()

        //1.拿到请求体
        val body = chain.request().body
        val buffer = Buffer()
        body?.writeTo(buffer)
        val bodyStr = buffer.toString()  //{text= {"{
//        "pId": 0,
//        "time": "string",
//        "uName": "string",
//        "uPwd": "string"
//    }"}}
        Log.i("TagA", "intercept:$bodyStr")
        buffer.close()
        //2.截取json数据
        val jsonStr = bodyStr.substring(bodyStr.indexOf("{"), bodyStr.lastIndexOf("}") + 1)
        Log.i("TagA", "intercept:$jsonStr")

        //3.获取键值对
        val sb = StringBuffer()
        val jsonObject = JSONObject(jsonStr)
        val keys = jsonObject.keys()
        while (keys.hasNext()) {
            val key = keys.next()
            val value = jsonObject.getString(key)
            //4.拼接签名
            sb.append(value)
        }

        //5.拼接秘钥
        sb.append("tamboo")
        Log.i("TagA", "intercept:${sb.toString()}")
        //6.MD5加密,并且转换为小写
        val sign = EncryptUtils.encryptMD5ToString(sb.toString()).toLowerCase()
        //7.新的请求bod
        jsonObject.put("sign", sign)
        Log.i("TagA", "intercept:$sign")
        val requestBody =
            RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), jsonObject.toString())
        builder.post(requestBody)
        request = builder.build()
        return chain.proceed(request)
    }
}